import type { RouteLocationNormalizedLoaded, Router } from "vue-router";

/**
 * 防抖函数
 * @param func 回调函数
 * @param wait 间隔时间
 * @returns 函数
 */
export function debounce<F extends FunctionArgs>(fn: F, wait = 0) {
    let timer: NodeJS.Timeout;
    const callback: FunctionArgs = (...args) => {
        timer && clearTimeout(timer);
        timer = setTimeout(() => {
            // @ts-ignore
            fn.apply(this, args);
        }, wait);
    };
    return callback;
}

/**
 * 节流函数
 * @param func 回调函数
 * @param wait 间隔时间
 * @returns 函数
 */
function throttle<F extends FunctionArgs>(fn: F, wait = 0) {
    let timer: NodeJS.Timeout;
    // 利用闭包延长变量声明周期
    const callback: FunctionArgs = (...args) => {
        if (!timer) {
            timer = setTimeout(() => {
                // @ts-ignore
                fn.apply(this, args);
                timer && clearTimeout(timer);
            }, wait);
        }
    };
    return callback;
}
/**
 * 格式化时间
 * @param time 需要格式化的时间
 * @returns 字符串时间
 */
function formatTime<T extends string | number | Date>(time: T) {
    const date = typeof time === "number" ? new Date(time) : new Date(time); // .replace(/-/g, "/")
    const diff = (new Date().getTime() - date.getTime() - 480000) / 1000;
    const dayDiff = Math.floor(diff / 86400);
    const isValidDate = Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date.getTime());
    if (!isValidDate) {
        console.error("不是有效日期格式");
    }
    const formatDate = function (date: Date) {
        const today = new Date(date);
        const year = today.getFullYear();
        const month = today.getMonth() + 1 + "";
        const day = today.getDate() + "";
        const hour = today.getHours() + "";
        const minute = today.getMinutes() + "";
        const second = today.getSeconds() + "";
        return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")} ${hour.padStart(2, "0")}:${minute.padStart(
            2,
            "0"
        )}:${second.padStart(2, "0")}`;
    };
    //小于0或者大于等于31显示原时间
    if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
        if (isNaN(dayDiff)) {
            return formatDate(new Date());
        }
        return formatDate(date);
    }
    return formatDate(date);
}

export const reloadComp = ($router:Router,$route:RouteLocationNormalizedLoaded) => {
    $router.push({
        query: {
            redirect: $route.path,
        },
        path: "/blank"
    });
};
